package org.restorator.dao.tx;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.restorator.exception.DataStoreException;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Snisar Bogdan.
 */
public class C3PoDataSourceFactory implements DataSourceFactory {

    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());


    private Properties props;
    private ComboPooledDataSource cpds;

    public C3PoDataSourceFactory() throws IOException, PropertyVetoException {
        props = new Properties();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(PROP_FILE_NAME);
        props.load(inputStream);
        setUp();
    }

    private void setUp() throws PropertyVetoException {
        cpds = new ComboPooledDataSource();
        cpds.setJdbcUrl(props.getProperty("jdbc.url"));
        cpds.setUser(props.getProperty("jdbc.user"));
        cpds.setPassword(props.getProperty("jdbc.password"));

        cpds.setDriverClass(props.getProperty("jdbc.driver"));
        cpds.setInitialPoolSize(new Integer(props.getProperty("jdbc.initialPoolSize")));
        cpds.setAcquireIncrement(new Integer(props.getProperty("jdbc.acquireIncrement")));
        cpds.setMaxPoolSize(new Integer(props.getProperty("jdbc.maxPoolSize")));
        cpds.setMinPoolSize(new Integer(props.getProperty("jdbc.minPoolSize")));
        cpds.setMaxStatements(new Integer(props.getProperty("jdbc.maxStatements")));

        logger.info("Inint c3po connection pool. Customs props: {}", props);
    }

    @Override
    public DataSource getDataSource() throws DataStoreException {
        return cpds;
    }

    @Override
    public Properties getDataSourceProperties() {
        return (Properties) props.clone();
    }

    @Override
    public void close() throws SQLException {
        cpds.close();
    }
}
